package net.example.activity.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.oraycn.esframework.core.ClientType;
import com.oraycn.esbasic.helpers.StringHelper;

import net.example.activity.ChatActivity;
import net.example.activity.FriendNotifyActivity;
import net.example.activity.GroupNotifyActivity;
import net.example.activity.ValidationMessageActivity;
import net.example.activity.adapter.SessionAdapter;
import net.example.manager.ClientGlobalCache;
import net.example.model.event.ChatEvent;
import net.example.manager.GGApplication;
import net.example.model.event.ClickToChatEvent;
import net.example.model.event.FriendDeletedNotifyEvent;
import net.example.model.event.GroupDeletedNotifyEvent;
import net.example.model.event.GroupInfoChangedEvent;
import net.example.model.event.RequestAddFriendEvent;
import net.example.model.event.RequestAddGroupEvent;
import net.example.model.event.UserEvent;
import net.example.db.LastChatRecordPersister;
import net.example.model.ChatInfo;
import net.example.model.common.ChatEventType;
import net.example.model.GGGroup;
import net.example.model.GGUser;
import net.example.model.event.UserInfoChangedEvent;
import net.example.ggtalk.R;
import net.example.utils.CommonOptions;
import net.example.utils.ConfigUtils;
import net.example.utils.IntentUtils;
import net.example.utils.LogHelper;
import net.example.activity.view.sessionview.MessageItem;
import net.example.activity.view.sessionview.SlidingDeleteListView;
import net.example.activity.view.sessionview.SlidingDeleteListView.IXListViewListener;
import net.example.activity.view.sessionview.SlidingDeleteSlideView;
import net.example.utils.ToastUtils;
import net.example.utils.android.AndroidUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import de.greenrobot.event.EventBus;

public class SessionFragment extends Fragment implements IXListViewListener,
        AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {
    private View mView;
    private Handler mHandler;
    private SlidingDeleteListView mListView;
    private List<MessageItem> mMessageItems = new ArrayList<MessageItem>();
    private MessageItem notifyMessageItem = new MessageItem();
    private SlidingDeleteSlideView mLastSlideViewWithStatusOn;
    private SessionAdapter sessionAdapter;
    private boolean isLoading = false;

    /**
     * 判断是否长按状态
     */
    private boolean isLongState = false;
    private ExecutorService executorService;
    /**
     * 记录选中listviw选中项
     */
    private HashMap<Integer, Boolean> checkedItemMap = new HashMap<Integer, Boolean>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_session, container, false);
        TextView tv_title = (TextView) mView.findViewById(R.id.message_title);
        tv_title.setText(R.string.session);
        mView.findViewById(R.id.plus_btn).setVisibility(View.GONE);
        init();
        executorService = Executors.newSingleThreadExecutor();
        return mView;
    }

    private void init() {
        try {
            isLongState = false;
            mHandler = new Handler();
            mListView = (SlidingDeleteListView) mView.findViewById(R.id.xListView);
            getMessageItems();
            sessionAdapter = new SessionAdapter(getActivity(), mMessageItems,
                    new onSlideListener(), new onDeleteListen());
            mListView.setPullLoadEnable(true);
            mListView.setEnableSlidingDelete(true);
            mListView.setAdapter(sessionAdapter);
            mListView.setOnItemClickListener(this);
            mListView.setOnItemLongClickListener(this);
            mListView.setXListViewListener(this);
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public int getMessageItemCount() {
        if (this.mMessageItems == null) {
            return 0;
        }
        return this.mMessageItems.size();
    }

    private void getMessageItems() {
        this.isLoading = true;
        mMessageItems.clear();
        List<MessageItem> list = LastChatRecordPersister.getInstance().getMyLastMessageRecord();
        List<MessageItem> tempList = new ArrayList();
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                MessageItem item = list.get(i);
                if (item.isGroup) {
                    if (ClientGlobalCache.getInstance().isGroupExist(item.senderID)) {
                        tempList.add(item);
                    }
                } else {
                    GGUser user = ClientGlobalCache.getInstance().getUser(item.senderID);
                    if (user != null) {
                        //if(user != null && !item.senderID.equals(OrayApplication.getInstance().getCurrentUser().getUserID())) {
                        item.userStatus = user.getUserStatus();
                        tempList.add(item);
                    }else {//特殊项 验证消息
                        tempList.add(item);
                    }
                }
            }
            mMessageItems.addAll(tempList);
        }
        this.isLoading = false;
    }

    public void getNewMessageItem() {
        getMessageItems();
        if (mHandler == null) {
            return;
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                sessionAdapter.notifyDataSetChanged();
                //    onLoad();
            }
        });
    }

    public void onEventMainThread(UserEvent event) {
        while (this.isLoading) {
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        for (MessageItem user : mMessageItems
        ) {
            if (user.senderID.equals(event.userID)) {
                user.userStatus = event.status;
                user.statusChanged = true;
                break;
            }
        }

        sessionAdapter.notifyDataSetChanged();
    }

    public void onEventMainThread(UserInfoChangedEvent event) {
        GGUser GGUser = ClientGlobalCache.getInstance().getUser(event.UserID);
        this.sessionInfoChanged(GGUser.getUserID(), GGUser.getCommentName());
    }

    public void onEventMainThread(GroupInfoChangedEvent event) {
        this.sessionInfoChanged(event.groupID, event.groupName);
    }

    public void onEventMainThread(RequestAddFriendEvent event) {
        GGUser user=ClientGlobalCache.getInstance().getUser(event.RequesterID);
        this.setValidationMessage(user.getCommentName()+"申请添加你为好友");
    }

    public void onEventMainThread(RequestAddGroupEvent event) {
        GGGroup group=ClientGlobalCache.getInstance().getGroup(event.GroupID);
        GGUser user=ClientGlobalCache.getInstance().getUser(event.RequesterID);
        this.setValidationMessage(user.getCommentName()+"申请加入"+group.getCommentName());
    }

    /*设置新被邀请加好友的数量*/
    private void setValidationMessage(String requestMsg) {
        try {
            //当前页面处于前台时，不设置未读消息
            if(AndroidUtil.isForeground(getActivity(), ValidationMessageActivity.class.getName())||AndroidUtil.isForeground(getActivity(), FriendNotifyActivity.class.getName())||AndroidUtil.isForeground(getActivity(), GroupNotifyActivity.class.getName()))
            {
                return;
            }
            boolean isNewItemMsg=false;
            MessageItem item = getMsgItem(CommonOptions.ValidationMessageID);
            if (item == null) {
                item = new MessageItem();
                item.title = "验证消息";
                item.time = new Date();
                item.senderID = CommonOptions.ValidationMessageID;
                item.unReadCount = 1;
                isNewItemMsg = true;
            }
            item.lastWord=requestMsg;
            if (isNewItemMsg) {
                mMessageItems.add(0, item);
            } else {
                if (mMessageItems.contains(item)) {
                    item.unReadCount++;
                    mMessageItems.remove(item);//从列表中移除，并添加到第一个
                }
                mMessageItems.add(0, item);
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    sessionAdapter.notifyDataSetChanged();
                    onLoad();
                }
            });
            LastChatRecordPersister.getInstance().addOrUpdate(item);
            ClientGlobalCache.getInstance().addNotReadMsg(CommonOptions.ValidationMessageID);
        } catch (Exception ex) {
            ToastUtils.showLongTemp(getActivity(), ex.getMessage());
        }
    }

    //用户或组资料变动
    private void sessionInfoChanged(String senderID, String sendName) {
        for (MessageItem item : mMessageItems
        ) {
            if (item.senderID.equals(senderID)) {
                if (!item.title.equals(sendName)) {
                    item.title = sendName;
                    LastChatRecordPersister.getInstance().addOrUpdate(item);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            sessionAdapter.notifyDataSetChanged();
                        }
                    });
                }
                break;
            }
        }
    }


    public void onEventMainThread(ClickToChatEvent event) {
        while (this.isLoading) {
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        MessageItem item = getMsgItem(event.friendID);
        if (item == null) {
            return;
        }
        item.isNewMsg = false;
        LastChatRecordPersister.getInstance().addOrUpdate(item);
    }


    public void onEventMainThread(ChatEvent event) {
        while (this.isLoading) {
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        try {
            if (event.isSystemMsg)//如果是系统消息，不触发也不记录到DB
            {
                return;
            }
            if (event.groupID.equals(GGApplication.getInstance().TALKINGUSER))//如果与该对象聊天界面打开
            {
                return;
            }
            //同设备同登录用户发送的RichChatMessage消息过滤
            if (event.clientType == ClientType.ANDROID && event.groupID.equals(GGApplication.getInstance().getCurrentUser().getUserID()) && event.type != ChatEventType.FileMessage) {
                return;
            }
            if (event.groupID.equals(GGApplication.getInstance().getCurrentUser().getUserID()) && !event.isEcho) {
                return;
            }
            boolean isNewItemMsg = false;
            MessageItem item = getMsgItem(event.groupID);
            if (item == null) {
                item = new MessageItem();
                item.unReadCount = 1;
                isNewItemMsg = true;
            }

            if (event.isGroupChat) {
                GGGroup group = ClientGlobalCache.getInstance().getGroup(event.groupID);
                GGUser user = ClientGlobalCache.getInstance().getUser(event.sourceID);
                if (group == null) {
                    return;
                }
                item.title = group.getName();
                item.time = event.occurrenceTime;
                item.senderID = event.groupID;
                item.lastWord = user == null ? "" : "[" + user.getName() + "]:" + LastChatRecordPersister.getInstance().getLastWord(event.msg);
                item.isGroup = true;
            } else {
                GGUser user = ClientGlobalCache.getInstance().getUser(event.groupID);
                if (user == null) {
                    return;
                }
                String sourceName = user.getName();
                item.title = sourceName;
                item.time = event.occurrenceTime;
                item.senderID = event.groupID;
                item.userStatus = user.getUserStatus();
                if (!StringHelper.isNullOrEmpty(event.snapchatMessageID)) {
                    item.lastWord = "[悄悄话]";
                } else {
                    if (event.type == ChatEventType.AudioMessage) {
                        item.lastWord = "[新语音]";
                    } else if (event.type == ChatEventType.FileMessage) {
                        item.lastWord = "[新文件]";
                    } else {
                        item.lastWord = LastChatRecordPersister.getInstance().getLastWord(event.msg);
                    }
                }
            }
            item.isNewMsg = !event.isEcho;
            if (isNewItemMsg) {
                mMessageItems.add(0, item);
            } else {
                if (mMessageItems.contains(item)) {
                    item.unReadCount++;
                    mMessageItems.remove(item);//从列表中移除，并添加到第一个
                }
                mMessageItems.add(0, item);
            }
            boolean onlineClientType4PC = ClientGlobalCache.getInstance().getMyOnlineClientTypeContainsPC();
            if (onlineClientType4PC) {
                item.unReadCount = 0;//若在PC端登陆，未读数量标记为0，不显示出来  （）
            }
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    sessionAdapter.notifyDataSetChanged();
                    onLoad();
                }
            });
            LastChatRecordPersister.getInstance().addOrUpdate(item);

            //  executorService.execute(new ChatInfoRunnable(event));
            if (!GGApplication.getInstance().TALKINGUSER.equals(event.groupID))//如果用户没有在聊天界面，则需要本地保存
            {
                ChatInfo info;
                if (event.type == ChatEventType.AudioMessage) {
                    info = ChatInfo.getChatInfo(event.audioMessage, new Date());
                } else if (event.type == ChatEventType.FileMessage) {
                    info = ChatInfo.getFileInfo(event.fileMessage, event.groupID, event.isEcho, new Date());
                    info.setFileHasDown(false);
                    info.setAcceptFile(true);
                } else {
                    if (!StringHelper.isNullOrEmpty(event.ImageUrl)) {
                        info = ChatInfo.getChatImg(event.sourceID, event.groupID, event.ImageUrl, true, event.msg.TransferTime);
                    } else {
                        info = ChatInfo.getChatInfo4Received(event.sourceID, event.groupID, event.msg, event.isEcho, event.msg.TransferTime);
                    }
                }
                info.setIsGroupChat(event.isGroupChat);
                info.setIsFromSession(true);
                info.snapchatMessageID = event.snapchatMessageID;
                ClientGlobalCache.getInstance().InsertChatMessageRecordInLocalDB(event.groupID, info);
                if (onlineClientType4PC)//若PC端在线，移除主面板 会话右上角移除 该会话者的未读数量。 若未在线就未读数+1
                {
                    ClientGlobalCache.getInstance().removeNotReadMsg(event.groupID);
                } else {
                    ClientGlobalCache.getInstance().addNotReadMsg(event.groupID);
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private class ChatInfoRunnable implements Runnable {
        private ChatEvent event;

        public ChatInfoRunnable(ChatEvent event) {
            this.event = event;
        }

        @Override
        public void run() {

//            if(event.isSystemMsg)//如果是系统消息，不需要保存到DB
//            {
//                return;
//            }
            if (!GGApplication.getInstance().TALKINGUSER.equals(event.groupID))//如果用户没有在聊天界面，则需要本地保存
            {
                ChatInfo info;
                if (event.type == ChatEventType.AudioMessage) {
                    info = ChatInfo.getChatInfo(event.audioMessage, new Date());
                } else if (event.type == ChatEventType.FileMessage) {
                    info = ChatInfo.getFileInfo(event.fileMessage, event.groupID, event.isEcho, new Date());
                    info.setFileHasDown(false);
                    info.setAcceptFile(true);
                } else {
                    if (!StringHelper.isNullOrEmpty(event.ImageUrl)) {
                        info = ChatInfo.getChatImg(event.sourceID, event.groupID, event.ImageUrl, true, event.msg.TransferTime);
                    } else {
                        info = ChatInfo.getChatInfo4Received(event.sourceID, event.groupID, event.msg, event.isEcho, event.msg.TransferTime);
                    }
                }
                info.setIsGroupChat(event.isGroupChat);
                info.setIsFromSession(true);
                ClientGlobalCache.getInstance().InsertChatMessageRecordInLocalDB(event.groupID, info);
            }
        }
    }


    public void onEventMainThread(FriendDeletedNotifyEvent event) {
        while (this.isLoading) {
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        for (MessageItem messageItem : mMessageItems
        ) {
            if (messageItem.senderID.equals(event.getGGUser().getUserID())) {
                mMessageItems.remove(messageItem);
                sessionAdapter.notifyDataSetChanged();
                LastChatRecordPersister.getInstance().delete(messageItem.senderID);
                return;
            }
        }
    }

    public void onEventMainThread(GroupDeletedNotifyEvent event) {
        while (this.isLoading) {
            try {
                Thread.sleep(100);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        for (int i = 0; i < mMessageItems.size(); i++) {
            MessageItem item = mMessageItems.get(i);
            if (item != null && item.senderID.equals(event.groupID)) {
                mMessageItems.remove(i);
                sessionAdapter.notifyDataSetChanged();
                LastChatRecordPersister.getInstance().delete(item.senderID);
            }
        }
    }

    public MessageItem getMsgItem(String userID) {
        MessageItem messageItem = null;
        for (int i = 0; i < mMessageItems.size(); i++) {
            MessageItem item = mMessageItems.get(i);
            if (item != null && item.senderID.equals(userID)) {
                messageItem = mMessageItems.get(i);
                break;
            }
        }
        return messageItem;
    }

    /**
     * @Function:加载更多，刷新完成
     */
    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("");// 刚刚
    }

    /**
     * @Function:回调刷新
     */
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getMessageItems();
                sessionAdapter.notifyDataSetChanged();
                onLoad();
            }
        }, 2000);
    }

    /**
     * @Function:回调加载更多
     */
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //geneItems();
                sessionAdapter.notifyDataSetChanged();
                onLoad();
            }
        }, 2000);
    }

    /**
     * @Function:长按监听
     */
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
                                   long arg3) {
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (currentItem != null) {
            currentItem.isNewMsg = false;
            MessageItem lastChatMessageItem = LastChatRecordPersister.getInstance().GetOneMessageItem(currentItem.senderID);
            if (lastChatMessageItem != null) {
                currentItem.lastWord = lastChatMessageItem.lastWord;
                this.moveItemToTop(currentItem);
            }
            currentItem = null;
        }
//        onRefresh();
    }

    @Override
    public void onDestroy() {
        executorService.shutdown();
        super.onDestroy();
    }

    private void moveItemToTop(MessageItem item) {
        mMessageItems.remove(item);
        mMessageItems.add(0, item);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                sessionAdapter.notifyDataSetChanged();
            }
        });
    }

    public void onDestroyView() {
        if (mView != null) {
            ((ViewGroup) mView.getParent()).removeView(mView);
        }
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private MessageItem currentItem;

    /**
     * @Function:点击监听
     */
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

        if (isLongState) {
            LogHelper.i("编辑状态下点击事件");
            putCheckedItemMap((int) arg3);
            updateListviewByDataSourceNoChange(true);
        } else {
            MessageItem item = (MessageItem) arg0.getItemAtPosition(arg2);
            if (item != null) {
                item.isNewMsg = false;
                item.unReadCount = 0;
                LastChatRecordPersister.getInstance().addOrUpdate(item);
                currentItem = item;
                sessionAdapter.notifyDataSetChanged();
                if (item.isGroup) {
                    IntentUtils.startActivityForString_Dubble(getActivity(), ChatActivity.class,
                            ConfigUtils.TalkingType, ConfigUtils.Group_Talking, ConfigUtils.Group_Talking, item.senderID);
                } else {
                    if(item.senderID.equals(CommonOptions.ValidationMessageID))
                    {
                        ClientGlobalCache.getInstance().removeNotReadMsg(CommonOptions.ValidationMessageID);
                        IntentUtils.startActivity(getActivity(), ValidationMessageActivity.class);
                        return;
                    }
                    IntentUtils.startActivityForString_Dubble(getActivity(), ChatActivity.class,
                            ConfigUtils.TalkingType, ConfigUtils.Person_Talking, ConfigUtils.Person_Talking, item.senderID);
                }
            }
        }
    }


    /**
     * @Function:收集选中listview item 状态
     */
    private void putCheckedItemMap(int key) {
        // checkedItemMap
        if (checkedItemMap.containsKey(key)) {
            boolean value = checkedItemMap.get(key);
            if (value) {
                checkedItemMap.remove(key);
            }
        } else {
            checkedItemMap.put(key, true);
        }
    }

    /**
     * @Function:强制刷新listview(数据源没有变化的情况)
     */
    private void updateListviewByDataSourceNoChange(boolean isLongState) {
        sessionAdapter.setIsLongState(isLongState);
        sessionAdapter.setCheckItemMap(checkedItemMap);
        sessionAdapter.notifyDataSetChanged();
        mListView.setAdapter(sessionAdapter);
        mListView.setSelectionFromTop();
    }


    @Override
    public void onScrollListener(int position) {
    }

    @Override
    public void onScrollListenerBottom() {
    }

    /**
     * @Function:删除监听
     */
    private class onDeleteListen implements SessionAdapter.OnDeleteListener {
        @Override
        public void onDelete(View view, int position) {
            MessageItem messageItem = mMessageItems.get(position);
            LastChatRecordPersister.getInstance().delete(messageItem.senderID);
            ClientGlobalCache.getInstance().DeleteChatMessageRecordInLocalDB(messageItem.senderID, messageItem.isGroup);
            mMessageItems.remove(position);
            sessionAdapter.notifyDataSetChanged();
        }
    }

    /**
     * @Function:监听选中listview item 项,保证选中只有一项是处于打开状态
     */
    private class onSlideListener implements
            SlidingDeleteSlideView.OnSlideListener {
        @Override
        public void onSlide(View view, int status) {
            if (mLastSlideViewWithStatusOn != null
                    && mLastSlideViewWithStatusOn != view) {
                mLastSlideViewWithStatusOn.shrink();
            }

            if (status == SLIDE_STATUS_ON) {
                mLastSlideViewWithStatusOn = (SlidingDeleteSlideView) view;
            }
        }
    }
}